<?php

namespace App\Http\Controllers\Admin\qyf;

use App\Common\Responses;
use App\Http\Controllers\Controller;
use App\Models\Comment;
use Illuminate\Http\Request;
class Comments extends Controller
{
    //评论&回复评论
    function comments(Request $request){
        //获取上级评论id
        $pid = (integer) $request->post('pid');
        //获取评论内容
        $comment= (string) $request->post('comment');
        //获取用户信息
        $email = (string) $request->post('email');
        $name = (string) $request->post('name');
        //初始化内容信息
        $param=[
            'name' => $name,
            'email' => $email,
            'comment'=>$comment,
            'status'=>1
        ];
        //内容审核
//            根据需求是否手动审核。
//            'status'=>1,2,3
        //判断上级评论是否为空，为空则添加评论一级不为空则判断上级评论是否存在且是否删除
        if (!empty($pid)){
            $comment= Comment::commentStatus($pid);
            if (empty($comment)) return Responses::error(['error'=>'不存在的评论信息！']);
            $param['parent_id']=$comment['id'];
            $param['status']="1";
            //回复一条评论
            Comment::topComments($param);
            return Responses::success(['success'=>true]);
        }
        //创建一条评论
        Comment::topComments($param);
        return Responses::success(['success'=>true]);
    }

    //查看当前评论下的评论
    function lookComments(Request $request){
        $id= (integer) $request->get('id');
        if (empty($id))$id=(int)0;
        $test=Comment::AllComments();
//        $data= Comment::lookComments($id);
        $data=$this->AllComments($test);
        //返回数据
        return Responses::success($data);
    }

    function AllComments($data,$id=0,$arr=[]){
        foreach ($data as $item => $value) {
            if ($value['parent_id'] == $id){
                $value['child']=$this->AllComments($data,$value['id']);
                $arr[]=$value;
            }
        }
        return $arr;
    }
    //修改评论
    function updateComments(Request $request){
        //获取当前评论id
        $id= $request->post('id');
        $comment=$request->post('comment');
        $upgrade=Comment::updateComments($id,$comment);
        return $upgrade?
            Responses::success(['message' => '修改成功']):
            Responses::error(['message' => '修改失败']);
    }
    //删除评论
    function deleteComments(Request $request){
        //获取当前评论id
        $id= $request->post('id');
        $upgrade=Comment::updateComments($id);
        return $upgrade?
            Responses::success(['message' => '删除成功']):
            Responses::error(['message' => '删除失败']);
    }
}
